use crate::model::{Article, PartialArticle};
use crate::utils;
use crate::Request;

// use sqlx::prelude::*;
use chrono::prelude::*;
use tide::http::mime;
use tide::prelude::json;
use tide::{Body, Response, StatusCode};

pub async fn index(request: Request) -> tide::Result {
    let pool = request.state().db.clone();
    let articles: Vec<Article> = Article::all(&pool).await?;

    let re = Response::builder(StatusCode::Ok)
        .content_type(mime::JSON)
        .body(Body::from_json(&articles)?)
        .build();
    Ok(re)
}

pub async fn show(request: Request) -> tide::Result {
    let pool = request.state().db.clone();
    let article: Article = Article::find_by_id(&pool, request.param("id")?).await?;

    let now = Local::now();

    let re = Response::builder(StatusCode::Ok)
        .content_type(mime::JSON)
        .body(json!({
            "code":1,
            "now local": now,
            "body": &article,
        }))
        .build();
    Ok(re)
}

pub async fn delete(request: Request) -> tide::Result {
    let pool = request.state().db.clone();
    Article::delete_by_id(&pool, request.param("id")?).await?;

    let re = Response::builder(StatusCode::Ok)
        .content_type(mime::JSON)
        .body(json!({"code":1}))
        .build();
    Ok(re)
}

pub async fn update(mut request: Request) -> tide::Result {
    let article: PartialArticle = utils::deserialize_body(&mut request).await?;
    let article_id = request.param("id")?;
    let pool = request.state().db.clone();

    let rows_updated = article.update_by_id(&pool, article_id).await?;

    let body = if rows_updated {
        json!({"code":1})
    } else {
        json!({"code":0})
    };

    let re = Response::builder(StatusCode::Ok)
        .content_type(mime::JSON)
        .body(body)
        .build();

    Ok(re)
}

pub async fn create(mut request: Request) -> tide::Result {
    let pool = request.state().db.clone();
    // let mut tx = db.begin().await?;
    // let article: PartialArticle = utils::deserialize_body(&mut request).await?;
    let article: PartialArticle = request.body_json().await?;

    let created_id = article.create(&pool).await?;

    let re = Response::builder(StatusCode::Ok)
        .content_type(mime::JSON)
        .body(json!({ "id": created_id }))
        .build();

    Ok(re)
}
